<template>
  <div class="meter-report-header">
    <MeterSelect ref="meterSelect" @meters-loaded="handleMetersLoaded"></MeterSelect>
  </div>
  <div class="container">
    <el-card class="meter-nav" v-loading="loading">
      <!-- 添加模糊搜索输入框 -->
      <div class="search-container">
        <el-input v-model="searchQuery" placeholder="搜索表计" clearable @input="handleSearch" class="search-input">
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
          <template #suffix>
            <span class="search-count" v-if="searchQuery">
              找到 {{ searchResultCount }} 个结果
            </span>
          </template>
        </el-input>
      </div>
      <MeterTree @refresh="handleRefresh" :data="displayTreeData"></MeterTree>
    </el-card>
    <div class="meter-report-card">
      <DeviceInfo @refresh="handleRefresh"></DeviceInfo>
    </div>
  </div>
</template>

<script setup>
import MeterTree from "@/components/meter/MeterTree.vue";
import { useMeterStore } from "@/stores/meter";
import { ref, watch, onMounted } from "vue";
import DeviceInfo from "./components/DeviceInfo.vue";
import MeterSelect from "@/components/meter/MeterSelect.vue";
import convertToTreeData from "@/utils/convertToTreeData";
import { debounce } from "@/utils/DebounceAndThrottle";
import { ElMessage } from "element-plus";
let meterStore = useMeterStore();
let loading = ref(false);
const meterList = ref([]);
const treeData = ref([]);
const displayTreeData = ref([]);
const searchQuery = ref('');
const searchResultCount = ref(0);
const meterSelect = ref(null);
const handleRefresh = async () => {
  try {
    await meterSelect.value.refresh();
    ElMessage.success('刷新成功');
  }
  catch (error) {
    handleError(error, '刷新失败');
  }
};
// 处理表计列表加载完成事件
const handleMetersLoaded = async (meters) => {
  loading.value = true;
  try {
    meterList.value = meters;
    // 转换为树形结构数据
    treeData.value = await convertToTreeData(meterList.value);
    // 设置显示用的树形数据
    displayTreeData.value = treeData.value;
    // 更新搜索结果计数
    searchResultCount.value = meterList.value.length;
    // 如果有表计数据，默认选择第一个
    if (treeData.value.length > 0) {
      meterStore.setCurrentMeter(treeData.value[0]);
    }
  } catch (error) {
    console.error('处理表计数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 模糊搜索方法
const fuzzySearch = (list, query) => {
  if (!query || query.trim() === '') {
    searchResultCount.value = list.length;
    return list;
  }

  const lowercaseQuery = query.toLowerCase();

  const results = list.filter(item => {
    // 递归检查对象的所有字段
    const checkObject = (obj) => {
      // 如果是基本类型，直接检查
      if (typeof obj === 'string' || typeof obj === 'number') {
        return obj.toString().toLowerCase().includes(lowercaseQuery);
      }

      // 如果是对象或数组，递归检查
      if (typeof obj === 'object' && obj !== null) {
        return Object.values(obj).some(value => checkObject(value));
      }

      return false;
    };

    return checkObject(item);
  });

  console.log('搜索结果数量:', results.length); // 调试信息
  searchResultCount.value = results.length;
  return results;
};

// 使用防抖处理搜索输入
const debouncedSearch = debounce(async () => {
  console.log('开始搜索...'); // 调试信息
  if (!searchQuery.value || searchQuery.value.trim() === '') {
    // 如果搜索框为空，显示全部数据
    displayTreeData.value = treeData.value;
  } else {
    // 搜索过滤数据
    const results = fuzzySearch(meterList.value, searchQuery.value);
    // 将搜索结果转换为树形结构
    displayTreeData.value = await convertToTreeData(results);
  }
}, 300);

// 处理搜索输入
const handleSearch = async () => {
  await debouncedSearch();
};

// 监听搜索查询变化
watch(searchQuery, async (newQuery) => {
  console.log('搜索查询变化:', newQuery); // 调试信息
  await handleSearch();
});

// 组件挂载时初始化
onMounted(() => {
  searchResultCount.value = meterList.value.length;
});
</script>

<style scoped>
.meter-report-header {
  margin: 0.5rem;
}

.container {
  display: flex;
  justify-content: space-between;
  height: 95%;
}

.meter-nav {
  flex: 1;
  border-radius: 4px;
  margin-right: 1rem;
  max-width: 18rem;
  overflow: auto;
}

.meter-report-card {
  flex: 3;
  border-radius: 4px;
  height: 100%;
  overflow-y: auto;
}

.meter-report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 1rem;
}

/* 搜索框样式 */
.search-container {
  margin-bottom: 1rem;
  padding: 0 0.5rem;
}

.search-input {
  width: 100%;
}

.search-count {
  font-size: 12px;
  color: #909399;
  margin-right: 8px;
}
</style>